package com.iscas.dataaggregation.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.iscas.dataaggregation.mapper.clickhouse", sqlSessionFactoryRef = "clickHouseSqlSessionFactory")
public class ClickHouseDataSourceConfig {

    @Bean(name = "clickHouseDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.clickhouse.hikari")
    public DataSource clickHouseDataSource() {
        return new HikariDataSource();
    }
//    @Bean(name = "clickHouseDataSource")
//    public DataSource clickHouseDataSource() {
//        HikariConfig config = new HikariConfig();
//        config.setJdbcUrl("jdbc:clickhouse://60.245.215.200:8123/default?useSSL=false");
//        config.setDriverClassName("com.clickhouse.jdbc.ClickHouseDriver");
//        config.setUsername("default");
//        config.setPassword("xQEyPLzlZt");
//        config.setMaximumPoolSize(10);  // 可调整连接池大小
//        config.setMinimumIdle(2);
//        config.setIdleTimeout(30000);
//        config.setMaxLifetime(1800000);
//        config.setConnectionTimeout(20000);
//        return new HikariDataSource(config);
//    }
    @Bean(name = "clickHouseSqlSessionFactory")
    public SqlSessionFactory clickHouseSqlSessionFactory(@Qualifier("clickHouseDataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        return sessionFactory.getObject();
    }

    @Bean(name = "clickHouseSqlSessionTemplate")
    public SqlSessionTemplate clickHouseSqlSessionTemplate(
            @Qualifier("clickHouseSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
